package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // begin    2024-10-17
        // end      2024-10-18
        // select sum(amount) from orders where order_time >= ? and order_time < ? and status = 5

        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<BigDecimal> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            BigDecimal amount = reportMapper.getTurnoverStatistics(beginTime, endTime, Orders.COMPLETED);
            turnoverList.add(amount);
        }
        if (turnoverList.size() == 0){
            turnoverList.add(BigDecimal.ZERO);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap<>();

            map.put("begin", beginTime);
            Integer totalUser = reportMapper.getUserStatistics(beginTime, endTime);
            totalUserList.add(totalUser);

            map.put("end", endTime);
            Integer newUser = reportMapper.getUserStatistics(beginTime, endTime);
            newUserList.add(newUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> totalOrderCountList =  new ArrayList<>();
        List<Integer> validOrderCountList =  new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);


            Integer totalCount = getOrderReportVO(beginTime, endTime, null);
            totalOrderCountList.add(totalCount);

            Integer validCount = getOrderReportVO(beginTime, endTime, Orders.COMPLETED);
            validOrderCountList.add(validCount);
        }
        Integer totalOrderCount = totalOrderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(totalOrderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    private Integer getOrderReportVO(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.getCountStatus(map);
    }

    /**
     * 销量排名top10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = reportMapper.getSalesTop10(beginTime, endTime);

        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");

        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) throws IOException {
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        LocalDateTime localDateTimeBegin =  LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime localDateTimeEnd =  LocalDateTime.of(dateEnd, LocalTime.MAX);
        Map map = new HashMap();
        map.put("begin", localDateTimeBegin);
        map.put("end", localDateTimeEnd);

        // 30天的总订单量
        Integer totalOrderCount = orderMapper.getCountStatus(map);
        // 30天的新增用户数
        Integer newUsers = userMapper.countByDate(map);

        map.put("status", Orders.COMPLETED);

        // 30天的营业额
        BigDecimal turnover = orderMapper.getTurnover(map);
        // 30天的有效订单量
        Integer validOrderCount = orderMapper.getCountStatus(map);
        // 30天的订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0){
            orderCompletionRate = (double) validOrderCount / totalOrderCount;
        }
        // 30天的平均客单价
        BigDecimal unitPrice = new BigDecimal(0);
        BigDecimal voc = new BigDecimal(validOrderCount);
        if (turnover.compareTo(BigDecimal.ZERO) != 0 && voc.compareTo(BigDecimal.ZERO) != 0){
            unitPrice = turnover.divide(voc);
        }

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);
        XSSFSheet sheet = excel.getSheetAt(0);
        sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);
        sheet.getRow(3).getCell(2).setCellValue(turnover.doubleValue());
        sheet.getRow(3).getCell(4).setCellValue(orderCompletionRate);
        sheet.getRow(3).getCell(6).setCellValue(newUsers);
        sheet.getRow(4).getCell(2).setCellValue(validOrderCount);
        sheet.getRow(4).getCell(4).setCellValue(unitPrice.doubleValue());

        for (int i = 0; i < 30; i++){
            LocalDate localDate = dateBegin.plusDays(i);
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map2 = new HashMap();
            map2.put("begin", beginTime);
            map2.put("end", endTime);

            // 总订单量
            Integer totalOrderCount2 = orderMapper.getCountStatus(map2);
            // 新增用户数
            Integer newUsers2 = userMapper.countByDate(map2);

            map2.put("status", Orders.COMPLETED);

            // 营业额
            BigDecimal turnover2 = orderMapper.getTurnover(map2);
            if (turnover2 == null){
                turnover2 = new BigDecimal(0);
            }
            // 有效订单量
            Integer validOrderCount2 = orderMapper.getCountStatus(map2);
            BigDecimal voc2 = new BigDecimal(validOrderCount2);
            // 订单完成率
            Double orderCompletionRate2 = 0.0;
            if (totalOrderCount2 != 0){
                orderCompletionRate2 = (double) validOrderCount2 / totalOrderCount2;
            }
            // 平均客单价
            BigDecimal unitPrice2 = new BigDecimal(0);
            if (turnover2.compareTo(BigDecimal.ZERO) != 0 && voc2.compareTo(BigDecimal.ZERO) !=0){
                unitPrice2 = turnover2.divide(voc2);
            }
            XSSFRow row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(localDate.toString());
            row.getCell(2).setCellValue(turnover2.doubleValue());
            row.getCell(3).setCellValue(validOrderCount2);
            row.getCell(4).setCellValue(orderCompletionRate2);
            row.getCell(5).setCellValue(unitPrice2.doubleValue());
            row.getCell(6).setCellValue(newUsers2);
        }
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);
        outputStream.close();
        excel.close();
    }
}